package com.zhao.dota.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.dota.model.Role;
import com.zhao.dota.service.RoleService;
import com.zhao.dota.struct.Result;
import com.zhao.dota.struct.SimpleParameters;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    @GetMapping("/")
    public Result<Page<Role>> list(SimpleParameters parameters) {
        Page<Role> page = new Page<>(parameters.getCurrent(), parameters.getSize());
        LambdaQueryWrapper<Role> query = Wrappers.lambdaQuery(Role.class);
        String search = parameters.getSearch();
        if (StringUtils.hasText(search)) {
            query.like(Role::getCode, search)
                    .or().like(Role::getName, search);
        }
        Page<Role> roles = roleService.page(page, query);
        return Result.success(roles);
    }

    @PostMapping("/")
    public Result<Role> save(Role role) {
        boolean b = roleService.saveOrUpdate(role);
        if (b) {
            return Result.success(role);
        }
        return Result.error();
    }

    @GetMapping("/{id}")
    public Result<Role> detail(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        return Result.success(role);
    }

    @GetMapping("/userRoles")
    public Result<List<Role>> userRoles(@RequestParam Integer userId) {
        List<Role> roles = roleService.findByUserId(userId);
        return Result.success(roles);
    }

}
